﻿using Furion.EventBus;
using Furion.JsonSerialization;
using Microsoft.Extensions.Logging;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.Application
{
    /// <summary>
    /// 队列
    /// </summary>
    [AllowAnonymous, ApiDescriptionSettings("Business", Name = "TestEventBus", Order = 2, Tag = "队列")]
    public class TestEventBus : IDynamicApiController
    {
        private readonly IEventPublisher _eventPublisher;
        private readonly IEventBusFactory _eventBusFactory;
        public TestEventBus(IEventPublisher eventPublisher, IEventBusFactory eventBusFactory)
        {
            _eventPublisher = eventPublisher;
            _eventBusFactory = eventBusFactory;
        }


        /// <summary>
        /// 发布 ToDo:Create 消息
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous, HttpGet("/TestEventBus/CreateDoTo"), ApiDescriptionSettings(Name = "TestEventBus"), NonUnify]
        public async Task CreateDoTo()
        {
            var modle = new SysFile
            {
                Id = Yitter.IdGenerator.YitIdHelper.NextId(),
                CreatedTime = DateTime.Now,
                CreatedUserId = 0,
                CreatedUserName = "admin",
                IsDeleted = false,
                ExtName = "admin",
                FileLength = 0,
                FileName = "file",
                FilePath = "file",
                OriginName = "admin",
                WebPath = "file"
            }; 

            await _eventPublisher.PublishAsync("ToDo:Create", modle.ToJson());
        }


        /// <summary>
        /// 高频
        /// </summary>
        [AllowAnonymous, HttpGet("/TestEventBus/HighFrequencyEvents"), ApiDescriptionSettings(Name = "TestEventBus"), NonUnify]
        public void HighFrequencyEvents()
        {
            var modle = new SysFile
            {
                CreatedTime = DateTime.Now,
                CreatedUserId = 0,
                CreatedUserName = "admin",
                IsDeleted = false,
                ExtName = "admin",
                FileLength = 0,
                FileName = "file",
                FilePath = "file",
                OriginName = "admin",
                WebPath = "file"
            };



            Parallel.For(0, 1000, (i) =>
            {
                modle.FileName = "file" + i;
                
                //_eventPublisher.PublishAsync("ToDo:Create", modle.ToJson());

                _eventPublisher.PublishDelayAsync("ToDo:Create", 500, modle.ToJson());
            });
        }


    }


    public class ToDoEventSubscriber : IEventSubscriber, ISingleton
    {
        private readonly ILogger<ToDoEventSubscriber> _logger;
        private readonly IJsonSerializerProvider _jsonSerializer;

        public ToDoEventSubscriber(ILogger<ToDoEventSubscriber> logger
            , IJsonSerializerProvider jsonSerializer)
        {
            _logger = logger;
            _jsonSerializer = jsonSerializer;
        }

        [EventSubscribe("ToDo:Create")]
        public async Task CreateToDo(EventHandlerExecutingContext context)
        {
            var todo = context.Source;

            var node = _jsonSerializer.Deserialize<SysFile>(todo.Payload.ToString());
            node.Id = Yitter.IdGenerator.YitIdHelper.NextId();
            string s = "";
            s += " \r\n " + node.FileName;
            s += " \r\n " + node.FilePath;
            s += " \r\n " + node.CreatedUserName;
            s += " \r\n " + node.WebPath;

            _logger.LogInformation("接收ToDo：", s);
            

            var rs = await App.GetService<IRepository<SysFile>>().InsertNowAsync(node);

             
            s += " \r\n 主键:" + rs.Entity.ToJson();

            Console.WriteLine(s);

            //_logger.LogInformation("创建一个 ToDo：{Name}", todo.Payload);

            _logger.LogInformation("主键：", s);

            await Task.CompletedTask;
        }

    }
}
